import { useEffect, useState } from "react";
import { S2DataConfig, S2Options, CellType, TooltipOperatorMenuInfo, S2CellType, HeaderIconClickParams } from "@antv/s2";
import citysPivot from '../data/citysPivot.json';
import { cloneDeep } from "lodash";
import { Button } from 'antd';
import { CaretUpOutlined, CaretDownOutlined, MinusOutlined } from '@ant-design/icons';
import styles from './PivotPage.less';

import { SheetComponent } from '@antv/s2-react';
import type { SheetComponentOptions } from '@antv/s2-react';
import '@antv/s2-react/dist/s2-react.min.css';

import { Menu } from 'antd';

export default function BaseTable() {

    const [cityData, setCityData] = useState<any[]>([]);

    const [dataCfg, setDataCfg] = useState<S2DataConfig>({
        fields: {
            rows: ['region', 'cityName'],
            columns: ['type', 'indicator'],
            values: ['value'],
            valueInCols: true,
        },
        meta: [
            { field: "type", name: "分类" },
            { field: "indicator", name: "指标" },
            { field: "value", name: "数据"},
            { field: "region", name: "区域" },
            { field: "cityName", name: "城市名" },
        ],
        data: cityData,
        
        // 配置初始排序，和点击排序不是一件事
        // 添加排序确保一致性
        sortParams: [
            // { sortFieldId: 'type', sortMethod: 'DESC' },
            { sortFieldId: 'indicator', sortMethod: 'DESC' },
        ]
    });

    const options: SheetComponentOptions = {
        hierarchyType: 'grid',
        cornerExtraFieldText: '自定义',
        frozen: {
            // rowCount: 1,
            // colCount: 2,
            // trailingColCount: 1,
        },
        style: {
            colCell: {
                widthByField: {
                    '面积(平方千米)': 150,
                    '等级': 150,
                    '行业类型': 150,
                },
            },
        },
        placeholder: {
            cell: "-",
            empty: {
                icon: "Empty",
                description: "暂无数据",
            },
        },
        showDefaultHeaderActionIcon: true,
        tooltip: {
            enable: true,
            style: {
                minWidth: '100px',
            },
            operation: {
                tableSort: true,
                hiddenColumns: false,//不显示tooltip中隐藏项
                menu: {
                    render: (props) => (
                        // 如果需要自己实现Menu，就一定要使用props.onClick，否则就没有点击排序效果了
                        <Menu
                            onClick={props.onClick}
                            defaultSelectedKeys={['1']}
                            defaultOpenKeys={['sub1']}
                            mode="inline"
                            items={[
                                {
                                    key: 'asc',
                                    label: '升序',
                                    icon: <CaretUpOutlined />
                                },
                                {
                                    key: 'desc',
                                    label: '降序',
                                    icon: <CaretDownOutlined />
                                },
                                {
                                    key: 'none',
                                    label: '不排序',
                                    icon: <MinusOutlined />
                                }
                            ]}
                        />
                    ),

                    // 如果使用默认的Props构建Menu，点击就有排序效果
                    // 如果自己构建Menu属性，点击就没有排序效果
                    // render: (props) => (<Menu {...props} />)
                },
            },
        },
    };

    useEffect(() => {
        const copy = cloneDeep(dataCfg);
        copy.data = cityData || [];
        setDataCfg(copy);
    }, [cityData]);

    return (
        <div className={styles.container}>
            <SheetComponent
                // 设置宽高自适应，传true默认只有宽度自适应
                adaptive={{width: true, height: true}}
                sheetType="pivot"
                dataCfg={dataCfg}
                options={options}
                onRangeSort={(params) => {  
                    console.log('排序参数:', params);  
                }}  
                onRangeSorted={(event) => {  
                    console.log('排序完成');  
                }} 
            />

            {!cityData?.length && (
                <Button style={{ position: 'absolute', top: 64, left: 60 }} onClick={() => {
                    setCityData(cleanData(citysPivot));
                }}>加载数据</Button>
            )}
        </div>
    );
}

// 清洗数据函数
const cleanData = (rawData: any[]) => {
    return rawData
        .map((item) => ({
            ...item,
            type: item.type?.toString().trim(),
            indicator: item.indicator?.toString().trim(),
            value: item.value,
        }))
        .filter((item) => item.type && item.indicator); // 移除空记录
};